const userMdel=require('../db/model/loginModel')
const exp =require('express')
const md5=require('md5')


let router=exp.Router()

router.get('/login',(req,res)=>{
  res.render('login.html')
})

router.post('/login',(req,res)=>{
  let {username,pwd}=req.body
  userMdel.findOne({username,pwd:md5(pwd)},(err,data)=>{
    // console.log(data);
    if(data){
      req.session.username=username
      res.redirect('/list')
    }else{
      res.send('抱歉，您输入账号或密码错误')
    }
  })
})

router.post('/register',(req,res)=>{
  let {username,pwd}=req.body
  userMdel.find({username},(err,data)=>{
    // console.log(data);
    if (data.length) {
      res.send('已有此账号，请登录或重新输入')
    }else{
      userMdel.create({username,pwd:md5(pwd)},(err,data)=>{
        req.session.username=username
        res.redirect('/list')
      })
    }
  })

})

router.get('/register',(req,res)=>{
  res.render('register.html')
})


router.get('/logout',(req,res)=>{
  req.session.destroy(()=>{
    res.redirect('/list')
  })
})

module.exports = router;